use BioProof;
use PLout;
use Mail::Send;
use strict;

while(1){
	my $f = new BioProof();
	if($f->GetFromDB() != 1){
		sleep 5;
		next;
	}

	print "file: " . $f->GetFile . "\n";
	my $info = new PLout($f);

	my $c = CheckCodons($f);
	$info->SetCodons($c);

	my $v = Verify($f);
	$info->SetVerify($v);

	my $out = $info->OutputHTML;
	my $file = $f->GetDir . "/results.html";
	my $tmp = $f->GetDir . "/tmp.html";
	open HTML, ">","$tmp" or die $!;
	print HTML $out;
	close HTML;
	`mv $tmp $file`;
	
	SendMail($f->GetEmail,$info->GetName,$info->OutputText);

	$f->Remove;
	print "\n";
}

sub CheckCodons {
	my $f = shift;

	return "" if($f->ToCheckCodons == 0);

	my $file = $f->GetFile;
	my $results = $f->GetDir . "/results.html";

	open VER , ">>$results"; 
	print VER "<br>Checking codons...";

	chdir "codons";
	my $out = "perl codons.pl -f ../$file -t " . $f->GetCodonTable;

	$out = `$out`;
	print VER "<b>done</b><br/\n";	
	close VER;
	chdir "../";
	return $out;
}

sub Verify {
	my $f = shift;

	return "" if($f->ToVerify == 0);
 
	my $file = $f->GetFile;
	my $results = $f->GetDir . "/results.html";
	open VER , ">>$results"; 
	print VER "<br>Starting verification of sequences...";

	my $keywords = $f->GetKeywords;
	chdir "seqverify";
	my $out = "./seqverify.pl -f ../$file $keywords";
	$out = `$out`;
	print VER "<b>done</b><br/\n";	
	close VER;
	chdir "../";
	return $out;
}

sub SendMail {
	my ($email,$subject,$message) = @_;
	return if $email eq "";
	my $msg = new Mail::Send;
	$msg->to($email);
	$msg->subject($subject);
	
	my $fh = $msg->open;
	print $fh $message;
	$fh->close;
}
